﻿using Authority.Model;
using AutoMapper.DTO;
using Common.Library;
using Dapper.MsSql.Library;
using Sql.DataBase;
using System;
using System.Collections.Generic;
using System.Linq;
using Tool.Model;
using Dapper.Library;
using Dapper.MySql.Library;

namespace Authority.Logic
{
    public class SysRoleServiceImpl : ISysRoleService
    {
        #region 查询信息

        /// <summary>
        /// 获取所有角色信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SysRoleEntity>> LoadAllListInfo()
        {
            var result = new ResultJsonInfo<List<SysRoleEntity>>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var listInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                if (listInfo.Count > 0)
                {
                    result.Code = ActionCodes.Success;
                    result.Data = listInfo;
                }
                else
                {
                    result.Msg = "无对应信息！";
                }
            }
            return result;
        }

        /// <summary>
        /// 根据Name获取角色列表信息
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<SysRoleEntity>> LoadListInfo(string sName)
        {
            var result = new ResultJsonInfo<List<SysRoleEntity>>();
            var listInfo = new List<SysRoleEntity>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                if (sName.IsNotNullOrEmpty())
                {
                    var allInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                    var rootInfo = allInfo.FindAll(p => p.sName.Contains(sName));
                    if (rootInfo.Count > 0)
                    {
                        listInfo.AddRange(rootInfo);
                        listInfo.AddRange(allInfo.GetChildList(rootInfo));
                        listInfo.OrderBy(p => p.iSort);
                    }
                    //con.QuerySql<SysRoleEntity>().BySql(DataCommandManager.GetSQLCommand("LoadRolesByName", "SysRole"), new { sName = sName }).Multiple();
                }
                else
                {
                    listInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                }
            }
            if (listInfo.Count > 0)
            {
                result.Code = ActionCodes.Success;
                result.Data = listInfo;
            }
            else
            {
                result.Msg = "无对应信息！";
            }
            return result;
        }

        /// <summary>
        /// 获取所有的可操作角色信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadSysRoleAllList()
        {
            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = con.QuerySet<SysRoleEntity>().WithNoLock().Multiple();

                if (result.Count > 0)
                {
                    var info = result.MapToList<SelectListInfo>();
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = info;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        #endregion

        #region 节点编辑操作

        /// <summary>
        /// 新增根节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddRoot(RoleRootRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                var sysRole = inputInfo.MapTo<SysRoleEntity>();

                //获取所有角色信息
                var sysRoleResult = con.QuerySet<SysRoleEntity>().WithNoLock().Multiple();
                double maxSort = 0;
                if (sysRoleResult.Count > 0)
                {
                    maxSort = sysRoleResult.Select(p => p.iSort).Max();
                }
                sysRole.gCode = GuidHelper.GetGuid();
                sysRole.iSort = maxSort + 1;
                sysRole.dCreateTime = DateTime.Now;
                sysRole.bIsSuperAdmin = false;

                result = con.CommandSet<SysRoleEntity>()
                       .IfNotExists(p => p.sName == sysRole.sName && p.bIsDeleted == false)
                       .Insert(sysRole);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "新增根节点信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败,请检查名称是否重复！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 新增子节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddChild(RoleChildRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                con.Transaction(tran =>
                {
                    var result = 0;

                    var sysRole = inputInfo.MapTo<SysRoleEntity>();

                    var sysRoleResult = tran.QuerySet<SysRoleEntity>().WithNoLock().Multiple();

                    //查询出排序在该节点之后的所有节点
                    var sysRoleInfos = sysRoleResult.FindAll(p => p.iSort >= sysRole.iSort);
                    foreach (var item in sysRoleInfos)
                    {
                        item.iSort = short.Parse((item.iSort + short.Parse("1")).ToString());
                        tran.CommandSet<SysRoleEntity>().Update(item);
                    }

                    //插入数据
                    sysRole.gCode = GuidHelper.GetGuid();
                    sysRole.dCreateTime = DateTime.Now;
                    sysRole.bIsSuperAdmin = false;
                    result = tran.CommandSet<SysRoleEntity>()
                           .IfNotExists(p => p.sName == sysRole.sName && p.bIsDeleted == false)
                           .Insert(sysRole);

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "新增子节点信息成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,请检查菜单名称是否重复！";
                    }
                });

            }
            return resultInfo;
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(RoleModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                var sysRole = inputInfo.MapTo<SysRoleEntity>();

                var sysRoleInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.gCode == sysRole.gCode).Single();
                if (sysRoleInfo != null)
                {
                    sysRoleInfo.sName = sysRole.sName;
                    sysRoleInfo.sContent = sysRole.sContent;
                    result = con.CommandSet<SysRoleEntity>()
                        .IfNotExists(p => p.gCode != inputInfo.gCode && p.sName == inputInfo.sName)
                        .Update(sysRoleInfo);
                }
                else
                {
                    resultInfo.Msg = "无对应角色信息！";
                }
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "修改角色信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败,请检查名称是否重复！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 删除信息
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;
                if (gCodeList.Count >= 0)
                {
                    //var listCode = con.QuerySql<string>().BySql(DataCommandManager.GetSQLCommand("LoadRolesByCodes", "SysRole"),
                    //new { gCodeList = gCodeList }).Multiple();

                    con.Transaction(tran =>
                    {

                        #region 获取当前选中节点和选中节点的子节点

                        var allInfo = tran.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                        var rootInfo = allInfo.FindAll(p => gCodeList.Contains(p.gCode));
                        var listInfo = new List<SysRoleEntity>();
                        if (rootInfo.Count > 0)
                        {
                            listInfo.AddRange(rootInfo);
                            listInfo.AddRange(allInfo.GetChildList(rootInfo));
                        }
                        var listCode = listInfo.Select(t => t.gCode).ToList();
                        #endregion

                        //判断角色是否被用户使用了，如果使用了，就不能被删除
                        var userRoleInfo = tran.QuerySet<SysUserRoleEntity>().AndWhere(p => listCode.Contains(p.gRoleCode)).Multiple();
                        if (userRoleInfo.Count == 0)
                        {
                            result = tran.CommandSet<SysRoleEntity>().AndWhere(p => listCode.Contains(p.gCode))
                                        .UpdateByExp(a =>
                                            new SysRoleEntity
                                            {
                                                bIsDeleted = true
                                            });

                            tran.CommandSet<SysRoleMenuEntity>().AndWhere(p => listCode.Contains(p.gRoleCode)).Delete();
                            tran.CommandSet<SysRoleButtonEntity>().AndWhere(p => listCode.Contains(p.gRoleCode)).Delete();

                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "操作成功！";
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "选中角色已被已被用户使用，无法删除！";
                        }
                    });
                }
                else
                {
                    resultInfo.Msg = "id为空，操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 角色授权
        /// <summary>
        /// 根据角色code和菜单code获取可操作按钮
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<RoleMenuButtonsListResponse>> LoadMenuButtonListByRoleMenuCode(RoleMenuButtonQueryRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<RoleMenuButtonsListResponse>>();
            List<RoleMenuButtonsListResponse> listInfo = new List<RoleMenuButtonsListResponse>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            {
                var info = con.QuerySet<View_RoleMenuButtonEntity>().AndWhere(p => p.gMenuCode == inputInfo.menuCode)
                                    //.AndWhere(p => p.gRoleCode == inputInfo.roleCode && p.gMenuCode == inputInfo.menuCode)
                                    //.OrWhere(p => p.gMenuCode == inputInfo.menuCode)
                                    .Multiple();
                if (info.Count>0)
                {
                    listInfo = info.MapToList<RoleMenuButtonsListResponse>();
                }
            }

            resultInfo.Code = ActionCodes.Success;
            resultInfo.Data = listInfo;
            resultInfo.Count = listInfo.Count;
            resultInfo.Msg = "获取成功！";
            return resultInfo;
        }

        /// <summary>
        ///  更改角色-菜单按钮关系表信息（给角色授按钮权限）
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyRoleMenuButtonInfo(RoleMenuButtonModifyRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {

                var sysRoleButtonList = new List<SysRoleButtonEntity>();
                foreach (var item in inputInfo.roleMenuButtonModifyInfo)
                {
                    sysRoleButtonList.Add(item.MapTo<SysRoleButtonEntity>());
                }

                con.Transaction(tran =>
                {

                    // 1、先删除sysRoleButtonList中没有，数据库库中有的。
                    string[] gCodeList = sysRoleButtonList.FindAll(p => p.gCode != null && p.gCode.IsNotNull() && p.gCode.ToLower() != "null").Select(p => p.gCode).ToArray();

                    tran.CommandSet<SysRoleButtonEntity>()
                                .AndWhere(p => p.gCode.WhereNotIn(gCodeList) && p.gRoleCode == inputInfo.gRoleCode && p.gMenuCode == inputInfo.gMenuCode)
                                .Delete();

                    foreach (var item in sysRoleButtonList)
                    {
                        if (item.gCode.IsNullOrEmpty() || item.gCode.ToLower() == "null")
                        {
                            item.gCode = GuidHelper.GetGuid();
                            tran.CommandSet<SysRoleButtonEntity>().Insert(item);
                        }
                        else
                        {
                            tran.CommandSet<SysRoleButtonEntity>().Update(item);
                        }
                    }
                });
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = 1;
                resultInfo.Msg = "操作成功！";
            }
            return resultInfo;
        }

        /// <summary>
        /// 给角色授菜单权限
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyRoleMenuInfo(RoleMenuModifyRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            //using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                con.Transaction(tran =>
                {

                    var menuCodes = inputInfo.gMenuCodeList;

                    #region 获取当前选中节点和选中节点的子节点

                    var allInfo = tran.QuerySet<SysMenuEntity>().AndWhere(p => p.bIsDeleted == false && p.bIsEnabled == true)
                                                                .OrderByAsc("iSort")
                                                                .Multiple();
                    var rootInfo = allInfo.FindAll(p => menuCodes.Contains(p.gCode));
                    var listInfo = new List<SysMenuEntity>();
                    if (rootInfo.Count > 0)
                    {
                        listInfo.AddRange(rootInfo);
                        listInfo.AddRange(allInfo.GetParentList(rootInfo));
                    }

                    menuCodes = listInfo.Distinct().Select(t => t.gCode).ToList();

                    #endregion

                    //获取该角色原有的菜单权限
                    var roleMenuListInfo = tran.QuerySet<SysRoleMenuEntity>()
                                    .AndWhere(p => p.gRoleCode == inputInfo.gRoleCode)
                                    .Multiple();

                    //1、获取需要删除的，删除掉。
                    var needRemoveRoleMenuListInfo = roleMenuListInfo.FindAll(p => !menuCodes.Contains(p.gMenuCode))
                                    .Select(p => p.gMenuCode)
                                    .ToArray();

                    //删除掉不用的菜单
                    tran.CommandSet<SysRoleMenuEntity>()
                                    .AndWhere(p => p.gMenuCode.WhereIn(needRemoveRoleMenuListInfo) && p.gRoleCode == inputInfo.gRoleCode)
                                    .Delete();

                    //2、获取需要增加的，增加上。
                    var needAddRoleMenuListInfo = menuCodes.ToList()
                                    .FindAll(p => !roleMenuListInfo.Select(roleMenu => roleMenu.gMenuCode).Contains(p));

                    SysRoleMenuEntity roleMenuItem = null;
                    foreach (var item in needAddRoleMenuListInfo)
                    {
                        roleMenuItem = new SysRoleMenuEntity();
                        roleMenuItem.gCode = GuidHelper.GetGuid();
                        roleMenuItem.gRoleCode = inputInfo.gRoleCode;
                        roleMenuItem.gMenuCode = item;

                        tran.CommandSet<SysRoleMenuEntity>().Insert(roleMenuItem);
                    }

                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = 1;
                    resultInfo.Msg = "操作成功！";

                });

            }
            return resultInfo;
        }
        #endregion
    }
}
